package cn.edu.anan.config;

import lombok.extern.slf4j.Slf4j;

/**
 * 数据源上下文环境
 *
 * @author ThinkPad
 * @version 1.0
 * @date 2021/9/21 16:02
 */
@Slf4j
public class DbContextHolder {

    /**
     * 写数据源标识
     */
    public static final String WRITE = "write";
    /**
     * 读数据源标识
     */
    public static final String READ = "read";

    /**
     * 本地线程绑定
     */
    private static ThreadLocal<String> contextHolder= new ThreadLocal<>();

    /**
     * 设置数据源类型
     * @param dbType
     */
    public static void setDbType(String dbType) {
        if (dbType == null) {
            log.error("dbType为空");
            throw new NullPointerException();
        }
        log.info("设置dbType为：{}",dbType);
        contextHolder.set(dbType);
    }

    /**
     * 获取数据源类型
     * @return
     */
    public static String getDbType() {
        return contextHolder.get() == null ? WRITE : contextHolder.get();
    }

    /**
     * 清除ThreadLocal
     */
    public static void clearDbType() {
        contextHolder.remove();
    }

}
